package com.ifinc.common.protocol.i8583.field;

import com.ifinc.common.utils.StringUtils;
import com.ifinc.common.utils.encode.BcdUtils;
import com.ifinc.common.utils.encode.ByteUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * User: luotao
 * Date: 13-11-15
 * Time: 13:41
 */
public class FieldVar extends AbstractField {

    public FieldVar() {
    }

    public FieldVar(int fieldLen) {
        super(fieldLen, true);
    }

    public FieldVar(int fieldLen, boolean joinBitMap) {
        super(fieldLen, joinBitMap);
    }

    @Override
    public byte[] toByte() {
         //定义的字段长度
        int define_len = String.valueOf(getFieldLen()).length();
        if(define_len%2!=0){
            define_len +=1;
        }

        //原始数据长度
        String src_len = String.valueOf(getSrcBytes().length);
        int value_len = src_len.length();

        String lenStr;
        if (define_len > value_len) {
            lenStr = StringUtils.leftPadWithBytes(src_len, define_len, '0', getEncoding());
        } else {
            lenStr = String.valueOf(getSrcBytes().length);
        }

        List<Byte> bytes = new ArrayList<Byte>();
        byte[] len_by = BcdUtils.str2Bcd(lenStr);
        bytes.addAll(ByteUtil.byteArray2List(len_by));
        bytes.addAll(ByteUtil.byteArray2List(str2byte(srcValue)));
        resBytes = ByteUtil.list2ByteArray(bytes);
        return setResDataInfo(resBytes);
    }

    @Override
    public byte[] toMacByte() {
        return new byte[0];
    }

    @Override
    public String getFieldType() {
        return VAR;
    }

    @Override
    public int toValue(byte[] data, int index) {
        return 0;
    }
}
